<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Experience;
use app\common\model\FamilyTree;
use app\common\model\PaymentLog;
use app\common\model\User;
use think\Db;

class Course extends Api{

    protected $noNeedLogin = ['lists'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    public function lists(){
        $userId = request()->post('user_id');
        $fId = request()->post('f_id');
        if(empty($userId) && empty($fId)){
            if($this->auth->id){
                $userId = $this->auth->id;
            }else{
                $this->error('请登陆后操作',[],401);
            }
        }
        if($userId){
            $count = FamilyTree::where('user_id',$userId)->where('shengyv','>','0')->count();
            if($count <= 0 && $userId != $this->auth->id){
                $this->error('流芳到期',[],3);
            }
            $fInfo = FamilyTree::where('user_Id',$userId)->find();
            $list = User::with('experience')->where('id',$userId)->field('id,nickname,mobile,avatar,bio,gender,birthday,education,seniority')->find();
        }else{
            $fInfo = FamilyTree::where('id',$fId)->find();
            if(empty($fInfo)){
                $this->error('参数错误');
            }
            if($fInfo['shengyv'] <= 0 && $fInfo['user_id'] != $this->auth->id){
                $this->error('流芳到期',[],3);
            }
            if($fInfo['user_id'] == 0){
                //echo '<pre>';print_r($fInfo->toArray());die;
                $list = [
                    'id'    => 0,
                    'nickname'=> $fInfo['name'],
                    'mobile'=> '',
                    'avatar'=> '',
                    'bio'   => '',
                    'gender'=>$fInfo['gender'],
                    'birthday'=>$fInfo['start_time'],
                    'seniority'=>$fInfo['seniority']
                ];
                $list['experience'] = Experience::where('f_id',$fInfo['id'])->select();
            }else{
                $list = User::with('experience')->where('id',$fInfo['user_id'])->field('id,nickname,mobile,avatar,bio,gender,birthday,education,seniority')->find();
            }
        }
        //$list = Experience::where('user_id',$this->auth->id)->order('start_time','desc')->select();

        $this->success(['liufang'=>$fInfo['liufang'],'shengy'=>$fInfo['shengyv']],$list);
    }

    /**
     * 详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function info(){
        $id = request()->post('id');
        if(empty($id) && empty($fid)){
            $this->error('参数错误');
        }
        $info = Experience::where('id',$id)->find();
        if(empty($info)){
            $this->error('参数错误');
        }
        $myFamily = FamilyTree::where('user_id',$this->auth->id)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        $info->is_edit = 1;
        $familyInfo = FamilyTree::where('id',$info['f_id'])->find();
        // 判断是否时我的上代与下代，或者是我自己
        $result = $this->checkFamily($familyInfo,$myFamily);
        if(!$result){
            if($myFamily['spouse_id'] != 0){
                $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                $result = $this->checkFamily($familyInfo,$spouse);
                if(!$result){
                    $info->is_edit = 0;
                }
            }else{
                $info->is_edit = 0;
            }
        }
        $this->success('请求成功',$info);
    }

    /**
     * 添加个人阅历
     */
    public function add()
    {
        $post = request()->post();
        $result = $this->validate($post,'CourseValidate.add');
        if($result !== true){
            $this->error($result);
        }

        $userId = $this->auth->id;
        $myFamily = FamilyTree::where('user_id',$userId)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        $fId = $myFamily['id'];
        // 当帮家庭成员添加时
        if(isset($post['f_id']) && !empty($post['f_id'])){
            // 查询家庭信息
            $familyInfo = FamilyTree::where('id',$post['f_id'])->find();
            if(empty($familyInfo)){
                $this->error('参数错误');
            }
            // 当不是族长添加
            if($familyInfo['family_id'] != $userId){
                // 判断是否时我的上代与下代，或者是我自己
                $result = $this->checkFamily($familyInfo,$myFamily);
                if(!$result){
                    if($myFamily['spouse_id'] != 0){
                        $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                        $result = $this->checkFamily($familyInfo,$spouse);
                        if(!$result){
                            $this->error('权限不足，无法编辑');
                        }
                    }else{
                        $this->error('权限不足，无法编辑');
                    }
                }
            }
            $userId = $familyInfo['user_id'];
            $fId = $familyInfo['id'];
        }
        Experience::create([
            'user_id'       => $userId,
            'start_time'    => $post['start_time'],
            'end_time'      => $post['end_time'],
            'content'       => $post['content'],
            'images'        => $post['images'] ?? '',
            'f_id'          => $fId,
        ]);
        return $this->success('添加成功');
    }

    /**
     * 编辑阅历
     * @throws \think\Exception
     */
    public function edit(){
        $post = request()->post();
        $result = $this->validate($post,'CourseValidate.edit');
        if($result !== true){
            $this->error($result);
        }
        $userId = $this->auth->id;
        $myFamily = FamilyTree::where('user_id',$userId)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        $fId = $myFamily['id'];
        $find = Experience::where('id',$post['exp_id'])->find();
        if(empty($find)){
            $this->error('阅历不存在');
        }
        if($find['user_id'] != $userId){
            // 查询家庭信息
            if($find['user_id'] != 0){
                $familyInfo = FamilyTree::where('user_id',$find['user_id'])->find();
            }else{
                $familyInfo = FamilyTree::where('id',$find['f_id'])->find();
            }
            if(empty($familyInfo)){
                $this->error('参数错误');
            }
            // 当不是族长添加
            if($familyInfo['family_id'] != $userId){
                // 判断是否时我的上代与下代，或者是我自己
                $result = $this->checkFamily($familyInfo,$myFamily);
                if(!$result){
                    if($myFamily['spouse_id'] != 0){
                        $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                        $result = $this->checkFamily($familyInfo,$spouse);
                        if(!$result){
                            $this->error('权限不足，无法编辑');
                        }
                    }else{
                        $this->error('权限不足，无法编辑');
                    }
                }
            }
            $userId = $familyInfo['user_id'];
            $fId = $familyInfo['id'];
        }
        Experience::where('id',$post['exp_id'])->update([
            'user_id'       => $userId,
            'start_time'    => $post['start_time'],
            'end_time'      => $post['end_time'],
            'content'       => $post['content'],
            'images'        => $post['images'] ?? '',
            'f_id'          => $fId,
        ]);
        $this->success('修改成功');
    }

    public function del(){
        $post = request()->post();
        $expId = request()->post('exp_id');
        $userId = $this->auth->id;
        $myFamily = FamilyTree::where('user_id',$userId)->find();
        if(empty($myFamily)){
            $this->error('参数错误!');
        }
        $find = Experience::where('id',$post['exp_id'])->find();
        if(empty($find)){
            $this->error('阅历不存在');
        }
        if($find['user_id'] != $userId){
            // 查询家庭信息
            if($find['user_id'] != 0){
                $familyInfo = FamilyTree::where('user_id',$find['user_id'])->find();
            }else{
                $familyInfo = FamilyTree::where('id',$find['f_id'])->find();
            }
            if(empty($familyInfo)){
                $this->error('参数错误');
            }
            // 当不是族长添加
            if($familyInfo['family_id'] != $userId){
                // 判断是否时我的上代与下代，或者是我自己
                $result = $this->checkFamily($familyInfo,$myFamily);
                if(!$result){
                    if($myFamily['spouse_id'] != 0){
                        $spouse = FamilyTree::where('id',$myFamily['spouse_id'])->find();
                        $result = $this->checkFamily($familyInfo,$spouse);
                        if(!$result){
                            $this->error('权限不足，无法编辑');
                        }
                    }else{
                        $this->error('权限不足，无法编辑');
                    }
                }
            }
        }
        Experience::destroy($expId);
        $this->success('删除成功');
    }


    public function getPayInfo(){
        $money = request()->post('money') * 1;
        $payMethod = request()->post('pay_method',1); // 1=支付宝,2=微信
        $userId = request()->post('user_id');
        $fId = request()->post('f_id');
        if(empty($money) || $money <= 0 || !in_array($payMethod,[1,2])){
            $this->error('参数错误');
        }
        if(!empty($userId)){
            $fId = FamilyTree::where('user_id',$userId)->value('id');
        }
        if(empty($userId) && empty($fId)){
            $this->error('参数错误');
        }
        if(!is_int($money)){
            $this->error('金额只能为整数');
        }
        //$money = 0.01;
        $orderNo = generateUniqid('ZF');
        PaymentLog::create([
            'pay_no'    => $orderNo,
            'user_id'   => $this->auth->id,
            'money'     => $money,
            'method'    => $payMethod,
            'types'     => 2,
            'f_id'      => $fId
        ]);
        return $this->success('请求成功',[
            'channel'=>$payMethod == 2 ? 0 : 1,
            'orderid'=> $orderNo,
            'title'  => '充值',
            'amount' => $money
        ]);
    }


    public function liufangRank(){
        //$fid = request()->post('f_id');
        //$userId = request()->post('user_id');
        //if(empty($fid) && empty($userId)){
        //    $this->error('参数错误');
        //}
        //if(!empty($userId)){
        //    $fid = FamilyTree::where('user_id',$userId)->value('id');
        //}
        //$info = FamilyTree::get($fid);
        //if(empty($info)){
        //    $this->error('参数错误');
        //}
        $rank = PaymentLog::with('user')->where('types',2)->where('status',1)->group('user_id')->field('id,user_id,sum(money) sums')->order('sums','desc')->page(1,10)->select();
        $notice = PaymentLog::with(['user','family'])->where('types',2)->where('status',1)->order('created_at','desc')->field('id,user_id,f_id,money')->page(1,10)->select();
        $this->success('请求成功',['rank'=>$rank,'notice'=>$notice]);
    }
}